package belf.migrate.plugin.sqlserver.listener;

import belf.migrate.plugin.sqlserver.antlr.TSqlParserBaseListener;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class SqlServerCharacteristicListener extends TSqlParserBaseListener {

    @Getter
    private boolean isXmlRef = false;

    @Getter
    private boolean isRowCount = false;

    public boolean hasXmlRef(ParseTree node) {
        ParseTree parent = node.getParent();
        if (parent != null && "ref".equalsIgnoreCase(node.getText()) && parent.getClass().getName().endsWith("Id_Context")) {
            if(parent.getParent() != null && parent.getParent().getClass().getName().endsWith("Full_column_nameContext")) {
                parent = parent.getParent().getParent();
                if (parent != null && parent.getClass().getName().endsWith("Value_methodContext")) {
                    parent = parent.getParent();
                    return parent != null && parent.getClass().getName().endsWith("Xml_data_type_methodsContext");
                }
            }
        }
        return false;
    }

    public boolean hasRowCount(ParseTree node) {
        ParseTree parent = node.getParent();
        return parent != null && node.getText().endsWith("ROWCOUNT") && parent.getClass().getName().endsWith("Primitive_expressionContext");
    }

    @Override
    public void visitTerminal(TerminalNode node) {

        // 判断是否是xml引用
        if (hasXmlRef(node)) {
            isXmlRef = true;
        }

        // 判断是否是rowcount
        if (hasRowCount(node)) {
            isRowCount = true;
        }
    }
}
